package com.xiaoyu.linkedArray;

/**
 * @program: DS_and_A
 * @description: 回文链表
 *
 *  输入: 1->2->2->1
 *  输出: true
 *
 * @author: YuWenYi
 * @create: 2021-05-17 20:52
 **/
public class isPalindrome_234 {
    //使用快慢指针+反转链表的方式,去减少空间复杂度
    public static boolean isPalindrome(ListNode head) {
        ListNode fast = head;
        ListNode slow = head;

        //找到链表的中间结点
        while (fast.next!=null){
            fast = fast.next;
            if (fast.next!=null){
                fast = fast.next;
            }
            slow = slow.next;
        }
        System.out.println(fast.val);
        System.out.println(slow.val);

        if (head.next!=null && slow == head){
            return head.val == head.next.val;
        }

        //反转后半截链表
        ListNode lastHalfHead = null;
        ListNode curr = slow;
        while (curr!=null){
            ListNode next = curr.next;
            //断尾
            curr.next = lastHalfHead;
            //添头
            lastHalfHead = curr;
            curr = next;
        }

        //比较前半段链表和后半段反转后的链表
        while (head!=null && lastHalfHead!=null){
            if (head.val != lastHalfHead.val){
                return false;
            }
            head = head.next;
            lastHalfHead = lastHalfHead.next;
        }
        return true;
    }

    //解法二: 将链表保存到数组中,然后再使用进行判断,这样就会简单很多

    public static void main(String[] args) {
        ListNode l1 = new ListNode(1,new ListNode(1,new ListNode(2,new ListNode(1,new ListNode(1)))));

        System.out.println(isPalindrome(l1));
    }
}
